package cn.icanci.loopstack.bic.sdk.thread;

import cn.icanci.loopstack.bic.sdk.burying.BuryingDTO;
import cn.icanci.loopstack.bic.sdk.properties.BicProperties;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;

/**
 *  数据缓存池
 *
 * @author icanci
 * @since 1.0 Created in 2023/08/21 15:49
 */
public class BicDataCachePool {
    private static BicProperties bicProperties;

    public static void setBicProperties(BicProperties bicProperties) {
        BicDataCachePool.bicProperties = bicProperties;
    }

    private static final LinkedBlockingQueue<BuryingDTO> QUEUE = new LinkedBlockingQueue<>();;

    public static void add(BuryingDTO burying) {
        QUEUE.add(burying);
    }

    public static synchronized List<BuryingDTO> take() {
        try {
            List<BuryingDTO> buryingDTOS = new ArrayList<>();

            if (QUEUE.isEmpty()) {
                return buryingDTOS;
            }

            if (bicProperties.isSynchronous()) {
                buryingDTOS.add(QUEUE.poll());
                return buryingDTOS;
            }

            long maxBatchSize = bicProperties.getMaxBatchSize();
            while (maxBatchSize-- > 0) {
                BuryingDTO take = QUEUE.poll();
                if (take == null) {
                    break;
                }
                buryingDTOS.add(take);
            }
            return buryingDTOS;
        } catch (Exception ignore) {
            return new ArrayList<>();
        }
    }
}
